package com.neusoft.bizcore.activiti.listener;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.task.IdentityLink;

import lombok.extern.slf4j.Slf4j;

/**
 * 多实例任务监听类，设置每个任务的委派人assignee
 */
@Slf4j
public class MutiInstanceNodeCreateListener implements TaskListener {

    private static final long serialVersionUID = 1L;

    @Override
    public void notify(final DelegateTask delegateTask) {
        System.out.println(this);
        final String exId = delegateTask.getExecutionId();
        final ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
        final RuntimeService runtimeService = engine.getRuntimeService();
        final TaskService taskService = engine.getTaskService();
        final Integer loopCounter = (Integer) runtimeService.getVariable(exId, "loopCounter");
        MutiInstanceNodeCreateListener.log.info("当前顺序：" + loopCounter);
        final Set<IdentityLink> identityLinks = delegateTask.getCandidates();

        if (!identityLinks.isEmpty()) {
            final List<String> links =
                    identityLinks.stream().map(IdentityLink::getUserId).sorted().collect(Collectors.toList());
            MutiInstanceNodeCreateListener.log.info("当前候选对象集合：" + links);
            if (loopCounter < identityLinks.size()) {
                taskService.claim(delegateTask.getId(), links.get(loopCounter));
                //                delegateTask.setAssignee(links.get(loopCounter));
                MutiInstanceNodeCreateListener.log.info("当前实例任务的执行人assignee：" + links.get(loopCounter));
            }
        }

    }

}
